<template>
  <div>
    <el-form ref="myform" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <div class="anthor">
        <div class="anthor-info">
          <div id="module1">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>基本信息</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="计划名称" required prop="name">
                    <el-input v-model="formItem.name" placeholder="请输入计划名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="维护部门" required prop="orgCode">
                    <treeselect
                      v-model="formItem.orgCode"
                      :multiple="false"
                      :options="availableOganizations"
                      placeholder="请选择部门"
                      @select="selcetOrg"
                      @input="inputOrg"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="执行人" prop="chargeUserName">
                    <el-input v-model="formItem.chargeUserName" placeholder="请选择执行人" @focus="handleUserIconClick" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="40">
                <el-col :span="8">
                  <el-form-item label="维护类别" required prop="modelCode">
                    <treeselect
                      v-model="formItem.modelCode"
                      :multiple="false"
                      :options="cmdbModels"
                      :load-options="loadOptions"
                      :disable-branch-nodes="true"
                      id-key="code"
                      label-key="name"
                      placeholder="请选择维护类别"
                      @select="selModel"
                      @input="selModelInput"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="维护规则" prop="ruleCode">
                    <el-select v-model="formItem.ruleCode" class="select_input" placeholder="请选择规则" @focus="ruleClick">
                      <el-option v-for="(item) in maintainRuleList" :key="item.code" :label="item.name" :value="item.code" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="状态" prop="status">
                    <el-radio v-for="(item) in status" :key="item.value" v-model="formItem.status" :label="item.value">{{ item.label }}</el-radio>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </div>
          <div id="module2">
            <div class="anthor-info-head">
              <i class="el-icon-document" /><span>维护对象</span>
              <div>
                <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleSelectInstances">添加</el-button>
                <el-button type="primary" size="mini" icon="el-icon-delete" @click="handleRemove">移除</el-button>
              </div>
            </div>
            <div class="anthor-info-body">
              <div class="table-app-container">
                <div class="fixed-table">
                  <!-- <el-form-item label="" prop="instancesArray"> -->
                  <PageableTable
                    prop="instancesArray"
                    :data="formItem.instancesArray"
                    :loading="false"
                    :table-height="160"
                    :disable-pageable="true"
                    :multiple-selected="true"
                    class="fixed-table-table"
                    @selection-change="tableSelection"
                  >
                    <el-table-column v-for="column in insideColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
                      <template slot-scope="scope">
                        <column-render :render="column.render" :row="scope.row" :column="column" />
                      </template>
                    </el-table-column>
                  </PageableTable>
                </div>
              </div>
              <!-- </el-form-item> -->
            </div>
          </div>
          <div id="module3">
            <div class="anthor-info-head"><i class="el-icon-document" /><span>维护周期</span></div>
            <div class="anthor-info-body">
              <el-row :gutter="40">
                <el-col :span="24">
                  <!-- <el-form-item label="" required prop="period"> -->
                  <cron v-model="formItem.period" prop="period" :value="formItem.period" :second-show="false" :minute-show="false" placeholder="请输入维护周期" />
                  <!-- </el-form-item> -->
                </el-col>
              </el-row>
            </div>
          </div>
          <anchor key="el-dialog__body" :xleft="1" :ytop="10" container=".el-dialog__body" :title-list="anchorList" />
        </div>
      </div>
    </el-form>
    <SelectDialog v-if="userSelDialogFormVisible" title="选择执行人" :append-to-body="true" :show="userSelDialogFormVisible" @on-ok="selectUserOk" @on-cancel="selectUserCancel">
      <UsersPage ref="usersTable" :for-selection="true" :multiple-selected="true" :org-code="formItem.orgCode" />
    </SelectDialog>
    <SelectDialog v-if="instanceSelDialogFormVisible" title="选择维护对象" width="60%" :append-to-body="true" :show="instanceSelDialogFormVisible" @on-ok="selectInstanceOk" @on-cancel="selectInstanceCancel">
      <instancesTable ref="instancesTable" :for-selection="true" :model-code="formItem.modelCode" />
    </SelectDialog>
  </div>
</template>

<script>
import Vue from 'vue'
import {
  // listByModelCode,
  listByModelCodeAndStatus } from '@neu/dcom-ui/api/maintainRule'
import {
  create,
  update,
  detail
} from '@neu/dcom-ui/api/maintainPlan'
import Cron from '@neu/biz-core/components/Cron'
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import UsersPage from '@neu/auth-ui/views/users/tables'
import * as organizations from '@neu/auth-ui/api/organization'
import { pureTree } from '@neu/dcom-ui/api/schema'
import instancesTable from '@neu/dcom-ui/views/instances/tables'
import PageableTable from '@neu/biz-core/components/PageableTable'
import Anchor from '@neu/biz-core/components/Anchor/index'

const formItem = {
  name: '',
  orgCode: null,
  orgName: '',
  chargeUserId: '',
  chargeUserCode: '',
  chargeUserName: '',
  status: 'created',
  modelCode: null,
  modelName: '',
  ruleCode: '',
  period: '',
  instancesArray: [],
  jsonObjs: ''
}
export default {
  name: 'MaintainPlanEditForm',
  components: {
    UsersPage,
    SelectDialog,
    Cron,
    instancesTable,
    PageableTable,
    Anchor
  },
  props: {
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      anchorList: [ // 锚点列表
        { id: 'module1', label: '基本信息' },
        { id: 'module2', label: '维护对象' },
        { id: 'module3', label: '维护周期' }
      ],
      /** CMDB模型树 */
      cmdbModels: null,
      /** CMDB实例 */
      cmdbInstances: null,
      /** 是否显示用户选择对话框 */
      userSelDialogFormVisible: false,
      /** 部门 */
      availableOganizations: [],
      /** 是否显示实例 */
      instanceSelDialogFormVisible: false,
      /** 启用状态 */
      status: [],
      // 运维规则
      maintainRuleList: [],
      /** 要移除的对象 */
      removeData: [],
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '计划名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 100) {
              callback(new Error('最多可输入100个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        orgCode: [{
          required: true,
          message: '维护部门不能为空',
          trigger: 'change'
        }],
        chargeUserName: [{
          required: true,
          message: '执行人不能为空',
          trigger: 'change'
        }],
        modelCode: [{
          required: true,
          message: '维护类别不能为空',
          trigger: 'change'
        }],
        period: [{
          required: true,
          message: '维护周期不能为空',
          trigger: 'blur'
        }],
        instancesArray: [{
          required: true,
          message: '维护对象不能为空',
          trigger: 'change'
        }]
      },
      modal: true,
      /** 是否初始化 */
      isUpdateInit: true,
      /** 是否需要停止服务 */
      suspendService: true,
      insideColumns: [
        // { title: 'ID', key: '_id' },
        { title: '唯一标识', key: 'code' },
        { title: '名称', key: 'name' }
        // { title: '模型', key: 'schemadefName' }
      ]
    }
  },
  watch: {
    id: function() {
      this.fetch()
    }
  },
  created() {
    this.fetch()
    organizations.tree().then(response => {
      this.availableOganizations = [response.data]
    })

    if (this.id !== -1) {
      this.status = [{ value: 'enable', label: '启用' }, { value: 'disable', label: '停用' }]
    } else {
      this.status = [{ value: 'created', label: '创建' }, { value: 'enable', label: '启用' }]
    }
  },
  methods: {
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          this.isUpdateInit = false
          this.formItem = {
            ...response.data
          }
          this.formItem.instancesArray = JSON.parse(this.formItem.jsonObjs)

          listByModelCodeAndStatus(this.formItem.modelCode, 'enable').then(response => {
            this.maintainRuleList = response.data
          })
        })
      } else {
        this.formItem = {
          ...formItem
        }
      }
    },
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (this.formItem.instancesArray.length === 0) {
              return this.$message({
                showClose: true,
                message: '维护对象不能为空',
                type: 'error'
              })
            }

            if (this.formItem.period === '' || this.formItem.period === null) {
              return this.$message({
                showClose: true,
                message: '维护周期不能为空',
                type: 'error'
              })
            }

            this.formItem.jsonObjs = JSON.stringify(this.formItem.instancesArray)
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.myform.resetFields()
      this.formItem.instancesArray = []
      this.formItem = { ...formItem }
    },
    loadOptions({ action }) {
      if (action === 'LOAD_ROOT_OPTIONS') {
        return pureTree().then(response => {
          this.cmdbModels = response.data
        })
      }
    },
    selModel(node) {
      if (this.formItem.modelCode !== node.code) {
        this.formItem.instancesArray = []
        this.formItem.ruleCode = null
      }
      this.formItem.modelName = node.name
      this.formItem.modelCode = node.code
    },
    selModelInput(value) {
      // listByModelCode(value).then(response => {
      //   this.maintainRuleList = response.data
      // })
      listByModelCodeAndStatus(value, 'enable').then(response => {
        this.maintainRuleList = response.data
      })
    },
    changeStatus(value) {
      this.formItem.status = value
    },
    /** 组织机构赋值 */
    selcetOrg(value) {
      if (this.formItem.orgCode !== value.code) {
        this.formItem.chargeUserId = ''
        this.formItem.chargeUserName = ''
        this.formItem.chargeUserCode = ''
      }
      this.formItem.orgName = value.title
    },
    inputOrg(value) {
      if (this.isUpdateInit) {
        this.formItem.chargeUserId = ''
        this.formItem.chargeUserCode = ''
        this.formItem.chargeUserName = ''
      }
      this.isUpdateInit = true
      if (value === undefined) {
        this.formItem.orgName = ''
      }
    },
    /** 选择用户按钮 */
    handleUserIconClick() {
      if (!this.formItem.orgCode) {
        this.$message({
          type: 'warning',
          message: '请选择部门!'
        })
        return
      }
      this.userSelDialogFormVisible = true
    },
    selectUserOk() {
      var users = this.$refs.usersTable.selections
      if (users.length > 1) {
        return this.$message({
          showClose: true,
          message: '只能选择一个用户',
          type: 'error'
        })
      }
      if (users.length < 1) {
        this.formItem.chargeUserId = ''
        this.formItem.chargeUserCode = ''
        this.formItem.chargeUserName = ''
      } else {
        this.formItem.chargeUserId = users[0].id
        this.formItem.chargeUserName = users[0].name ? users[0].name : users[0].username
        this.formItem.chargeUserCode = users[0].username
      }
      this.userSelDialogFormVisible = false
    },
    selectUserCancel() {
      this.userSelDialogFormVisible = false
    },
    ruleClick() {
      if (!this.formItem.modelCode) {
        this.$message({
          type: 'warning',
          message: '请选择维护类别'
        })
        return
      }
    },
    instanceClick() {
      if (!this.formItem.modelCode) {
        this.$message({
          type: 'warning',
          message: '请选择维护类别'
        })
        return
      }
    },
    /** 选择对象 */
    handleSelectInstances() {
      if (!this.formItem.modelCode) {
        this.$message({
          type: 'warning',
          message: '请选择维护类别'
        })
        return
      }
      this.instanceSelDialogFormVisible = true
    },
    /** 删除某一项 */
    handleRemove() {
      if (this.removeData.length === 0) {
        return this.$message({
          showClose: true,
          message: '请选择一个对象',
          type: 'error'
        })
      }

      this.removeData.forEach(t => {
        this.formItem.instancesArray.forEach((item, index) => {
          if (item.code === t) {
            Vue.delete(this.formItem.instancesArray, index)
          }
        })
      })
    },
    tableSelection(sel) {
      this.removeData = sel.map(a => a.code)
    },
    selectInstanceOk() {
      const instances = this.$refs.instancesTable.selections
      const instanceCodes = this.formItem.instancesArray.map(a => a.code)
      const difference = instances.filter(t => {
        return !instanceCodes.includes(t.code)
      })
      this.formItem.instancesArray.push(...difference)
      this.instanceSelDialogFormVisible = false
    },
    selectInstanceCancel() {
      this.instanceSelDialogFormVisible = false
    }
  }

}
</script>
